<template>
  <div>
    <!--搜索栏-->
    <el-form :inline="true" :model="conditionForm" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="conditionForm.roleName" placeholder="请输入角色名称" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="init(1)" style="margin-left: 50px">查询</el-button>
        <el-button type="info" @click="handleAdd">添加</el-button>
        <el-button type="success" @click="refresh" style="margin-left: 50px">刷新</el-button>
      </el-form-item>
    </el-form>
    <!--表单数据-->
    <el-table
        :data="roleForm"
        style="width: 100%;">
      <el-table-column
          prop="roleName"
          label="角色名称"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="roleKey"
          label="角色权限符号"
          width="120"
      >
      </el-table-column>
      <!--      <el-table-column-->
      <!--          prop="dataScope"-->
      <!--          label="数据范围"-->
      <!--          width="120"-->
      <!--          :formatter="getDataScope"-->
      <!--      >-->
      <!--      </el-table-column>-->
      <el-table-column
          prop="status"
          label="角色状态"
          :formatter="getRoleStatus"
      >
      </el-table-column>
      <el-table-column
          prop="createBy"
          label="创建人"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="updateBy"
          label="更新人"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="更新时间"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="remark"
          label="备注"
          width="100"
      >
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="250">
        <template v-slot="scope">
          <el-button type="primary" size="small" :disabled="scope.row.roleId===1" @click="givePerms(scope.row)">
            角色授权
          </el-button>
          <el-button type="success" size="small" @click="handleEdit(scope.row)" :disabled="scope.row.roleId===1">编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteRole(scope.row)" :disabled="scope.row.roleId===1">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--弹出编辑表单-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="Form">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input
              v-model="Form.roleName"
              autocomplete="off"
              placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色权限符号" :label-width="formLabelWidth">
          <el-input
              v-model="Form.roleKey"
              autocomplete="off"
              placeholder="请输入角色权限符号"
          ></el-input>
        </el-form-item>
        <!--        <el-form-item label="数据范围" :label-width="formLabelWidth">-->
        <!--          <el-radio v-model="Form.dataScope" label="1">全部数据权限</el-radio>-->
        <!--          <el-radio v-model="Form.dataScope" label="2">自定义数据权限</el-radio>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色状态" :label-width="formLabelWidth">
          <el-radio v-model="Form.status" label="0">启用</el-radio>
          <el-radio v-model="Form.status" label="1">停用</el-radio>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
              v-model="Form.remark"
              autocomplete="off"
              placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--弹出添加表单-->
    <el-dialog :title="title" :visible.sync="dialogAddFormVisible">
      <el-form :model="addForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input
              v-model="addForm.roleName"
              autocomplete="off"
              placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色权限符号" :label-width="formLabelWidth">
          <el-input
              v-model="addForm.roleKey"
              autocomplete="off"
              placeholder="请输入角色权限符号"
          ></el-input>
        </el-form-item>
        <!--        <el-form-item label="数据范围" :label-width="formLabelWidth">-->
        <!--          <el-radio v-model="addForm.dataScope" label="1">全部数据权限</el-radio>-->
        <!--          <el-radio v-model="addForm.dataScope" label="2">自定义数据权限</el-radio>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色状态" :label-width="formLabelWidth">
          <el-radio v-model="addForm.status" label="0">启用</el-radio>
          <el-radio v-model="addForm.status" label="1">停用</el-radio>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
              v-model="addForm.remark"
              autocomplete="off"
              placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>
    <!--分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[1,2,5,10]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 添加权限时，弹出的树形菜单 -->
    <el-dialog title="权限树" :visible.sync="menuTreeVisible">
      <!-- check-strictly	:在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false -->
      <el-tree
          :data="data"
          :props="defaultProps"
          node-key="menuId"
          show-checkbox
          ref="menuTree"
          :check-strictly="checkStrictly"
          :default-checked-keys="nodeChecked"
          default-expand-all
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolePermissions">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Role",
  data() {
    return {
      //授予权限
      menuTreeVisible: false,
      data: [], //权限树数组对象
      defaultProps: {
        //父对象传值
        children: 'children',
        label: 'menuName',
      },
      checkStrictly: false, //先设置父节点和子节点的关系为false

      //搜索表单
      conditionForm: {},
      //角色列表
      roleForm: [],
      searchForm: {
        //分页
        currentPage: 1,
        pageSize: 5,
      },
      total: 0,
      staffInfo: {},//登陆者信息
      title: "角色添加", //默认值为部门添加
      formLabelWidth: "120px", //名称的宽度
      //编辑表单
      dialogFormVisible: false,
      Form: {
        roleId: "",
        roleName: "",
        roleKey: "",
        roleSort: "",
        dataScope: "",
        status: "",
        delFlag: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        remark: "",
      }, //编辑表单
      //添加表单
      dialogAddFormVisible: false,
      addForm: {},//添加表单
      nodeChecked: [],//勾选项目数组对象,该数组中的会自动勾选
      roleId: 0
    }
  },
  created() {
    this.init();
    this.initInfo();
  },
  methods: {
    //初始化加载个人信息
    initInfo() {
      this.$http.get("/system/user/info").then((res => {
        if (res.data.code === 200) {
          this.staffInfo = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }));
    },
    //分页查询
    init(val) {
      if (val === 1) {
        this.searchForm.roleName = this.conditionForm.roleName;
        this.searchForm.currentPage = 1;
      }
      this.$http.post("/userManagement/role/selectRoleByPage", this.searchForm).then((res => {
        if (res.data.code === 200) {
          this.roleForm = res.data.data.records;
          this.total = res.data.data.total;
        } else {
          this.$message.error("系统繁忙");
        }
      }))
    },
    //刷新
    refresh() {
      this.conditionForm = {};
      this.searchForm.roleName = "";
      this.searchForm.currentPage = 1;
      this.searchForm.pageSize = 5;
      this.init();
    },
    //添加表单弹出
    handleAdd() {
      //让对话框显示
      this.dialogAddFormVisible = true;
      this.title = "角色添加";
      //让form清空
      this.addForm = {};
      this.addForm.status = "0"; //默认角色启用
    },
    //更改每页显示条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.init();
    },
    //更改当前页码数
    handleCurrentChange(val) {
      this.searchForm.currentPage = val;
      this.init();
    },
    //格式化
    getRoleStatus(row) {
      if (row.status === "0") {
        return "启用";
      } else {
        return "禁用";
      }
    },
    getDataScope(row) {
      if (row.dataScope === "1") {
        return "全部数据权限";
      } else {
        return "自定数据权限";
      }
    },
    //弹出编辑表单
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.title = "角色编辑";
      this.Form = row;
    },
    //取消
    cancel() {
      this.dialogFormVisible = false;
      this.dialogAddFormVisible = false;
      this.init();
      this.Form = {};
      this.addForm = {};
    },
    //更新角色
    updateForm() {
      //编辑的数据是否合法
      if (this.Form.roleName.length === 0) {
        this.$message.error("角色名称不能为空");
        return;
      }
      //更新
      this.$http.post("/userManagement/role/updateRoleInfo?username=" + this.staffInfo.userName, this.Form).then((res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg);
          this.init();
          this.dialogFormVisible = false;
        } else {
          this.$message.error(res.data.msg);
        }
      }))
      //刷新左侧栏
      this.leftMenu();
    },
    //添加角色
    add() {
      //编辑的数据是否合法
      if (this.addForm.roleName === undefined || this.addForm.roleName.length === 0) {
        this.$message.error("角色名称不能为空");
        return;
      } else if (this.addForm.roleKey === undefined || this.addForm.roleKey.length === 0) {
        this.$message.error("角色权限符号不能为空");
        return;
      }
      //添加
      this.$http.post("/userManagement/role/addRole?username=" + this.staffInfo.userName, this.addForm).then((res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg);
          this.init();
          this.dialogAddFormVisible = false;
        } else {
          this.$message.error(res.data.msg);
        }
      }))
    },
    //刷新左侧栏
    leftMenu() {
      this.$http.get("/system/menu/leftMenu").then((res => {
        //获取菜单数据
        if (res.data.code === 200) {
          this.menuData = res.data.data;
        }
      }))
    },
    //删除
    deleteRole(row) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row);
        this.$http.get("/userManagement/role/deleteRole?roleId=" + row.roleId).then((res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            //刷新
            this.refresh();
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取角色的授权信息
    givePerms(row) {
      /*
      查询树形的权限树（key为menuId, label为menuName），选择根据权限key（menuId）选中
       */
      //获取角色id
      this.roleId = row.roleId;
      //1.查询权限树
      this.$http.get("/userManagement/menu/selectAll").then(res => {
        //2拿到查询到的所有权限 赋值给变量tmpData
        let tmpData = res.data.data;
        //3,根据角色ID查出权限菜单Id 赋值给nodeChecked，把该角色拥有的权限自动勾选上
        this.$http.get("/userManagement/menu/selectRoleMenus?roleId=" + this.roleId).then((res => {
          this.data = tmpData;
          this.checkStrictly = true;//使回显数据时把check-strictly绑定的属性值设置为true，实现父节点选中后，子节点不会全部选中
          this.$nextTick(() => {
            this.$refs.menuTree.setCheckedKeys(res.data.data); //给树节点赋值回显，将查询到到的为选中状态
            this.checkStrictly = false; //重点：赋值完成后重新设置为false
          });
          this.nodeChecked = res.data.data;//角色拥有的权限，用上面的赋值方法
        }))
      });
      //显示权限菜单对话框
      this.menuTreeVisible = true;
    },

    //给角色添加权限
    addRolePermissions() {
    // 获取重新选中的子节点
    let i;
    // getCheckedNodes(): 若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点所组成的数组
    let nodes = this.$refs.menuTree.getCheckedNodes();

    // 获取重新选中的父节点
    // getHalfCheckedKeys(): 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
    let nodesA = this.$refs.menuTree.getHalfCheckedKeys();

    // 判断至少选中一个节点
    if (nodes.length < 1) {
        this.$message.error("至少选中一个节点");
        return; // 让代码终止运行
    }

    let tempMenuIds = []; // 定义变量 存储权限id
    // 循环遍历，把选中的权限id赋值给变量
    for (i = 0; i < nodes.length; i++) {
        tempMenuIds.push(nodes[i].menuId);
    }

    for (i = 0; i < nodesA.length; i++) {
        tempMenuIds.push(nodesA[i]);
    }

    if (this.roleId === 1) {
        this.$message({
            message: "该角色为超级管理员，不能减少权限！",
            center: true,
        });
        this.menuTreeVisible = false; // 关闭权限菜单对话框
        return;
    }

    console.log("拥有的权限" + tempMenuIds);
    console.log("角色id" + this.roleId);

    // 发送 POST 请求
    this.$http.post("/userManagement/menu/addMenuByRole?roleId=" + this.roleId, tempMenuIds).then((res => {
        if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.menuTreeVisible = false;
            this.init();
            this.leftMenu();
        } else {
            this.$message.error(res.data.msg);
        }
    }))
},
  }

}
</script>
<style scoped>

</style>